package cn.openea.perpartner.meily.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.openea.perpartner.common.core.constant.Constants;
import cn.openea.perpartner.common.redis.service.RedisCache;
import cn.openea.perpartner.meily.web.entity.Corp;
import cn.openea.perpartner.meily.web.mapper.CorpMapper;
import cn.openea.perpartner.meily.web.service.ICorpService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * (CorpAccount)表服务实现类
 *
 * @author Weird077
 * @since 2023-05-19 11:32:42
 */
@Slf4j
@Service("corpAccountService")
public class CorpServiceImpl extends ServiceImpl<CorpMapper, Corp> implements ICorpService {
    @Value("${tencent.corp.id}")
    private String corpid;
    @Value("${tencent.corp.secret}")
    private String corpsecret;
    @Autowired
    private RedisCache redisCache;
    private final static String ACCOUNT_LIST = "https://qyapi.weixin.qq.com/cgi-bin/kf/account/list?access_token=";
    private final static String ACCOUNT_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/add_contact_way?access_token=";

    @Override
    public List<Corp> getAccountList() {

        return list(Wrappers.<Corp>lambdaQuery().orderByDesc(Corp::getUpdateTime));
    }

    @Override
    public String getAccountUrl(String openKfId) {
        String key = getKey(openKfId);
        String accountUrl = redisCache.getCacheObject(key);
        if (StrUtil.isNotBlank(accountUrl)) {
            return accountUrl;
        }
        Corp corp = getById(openKfId);
        if (BeanUtil.isNotEmpty(corp)) {
            accountUrl = corp.getKfUrl();
        }
        if (StrUtil.isNotBlank(accountUrl)) {
            redisCache.setCacheObject(key, accountUrl);
            return accountUrl;
        }
        String url = ACCOUNT_URL.concat(getAccessToken());
        JSONObject params = new JSONObject();
        params.put("open_kfid", openKfId);
        JSONObject result = doPost(url, params);
        if (result.getString("errmsg").equals("ok")) {
            accountUrl = result.getString("url");
        }
        redisCache.setCacheObject(key, accountUrl);
        return accountUrl;
    }

    @Override
    public boolean syncKfAccount() {
        JSONObject object = new JSONObject();
        int cycles = 50;
        int offset = 0;
        int limit = 100;
        List<Corp> corpList = new ArrayList<>();
        for (int i = 0; i < cycles; i++) {
            object.put("offset", offset);
            object.put("limit", limit);
            String url = ACCOUNT_LIST.concat(getAccessToken());
            JSONObject result = doPost(url, object);
            if (result.getString("errmsg").equals("ok")) {
                JSONArray list = result.getJSONArray("account_list");
                if (list.isEmpty()) {
                    break;
                }
                for (int j = 0; j < list.size(); j++) {
                    JSONObject account = list.getJSONObject(j);
                    Corp corp = Corp.builder()
                            .openKfid(account.getString("open_kfid"))
                            .name(account.getString("name"))
                            .avatar(account.getString("avatar"))
                            .build();
                    corpList.add(corp);
                }
                offset += limit;
            }
        }
        // 获取客服链接
        corpList.forEach(corp -> {
            String url = ACCOUNT_URL.concat(getAccessToken());
            JSONObject params = new JSONObject();
            params.put("open_kfid", corp.getOpenKfid());
            corp.setKfUrl(doPost(url, params).getString("url"));
            redisCache.setCacheObject(getKey(corp.getOpenKfid()), corp.getKfUrl());
        });
        return saveOrUpdateBatch(corpList);
    }

    @Override
    public List<Corp> getList(Corp corp) {
        LambdaQueryWrapper<Corp> wrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotBlank(corp.getName())){
            wrapper.like(Corp::getName, corp.getName());
        }
        wrapper.orderByDesc(Corp::getUpdateTime);
        List<Corp> list = list(wrapper);

        if(list.size() < 1){
            // 查不到数据时，默认返回“广州市开放邑软件科技有限公司客服”
            LambdaQueryWrapper<Corp> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(Corp::getName, "玫丽平台");
            list = list(queryWrapper);
        }
        return list;
    }

    @Override
    public String getKFUrl(String openKfId, String name) {

        String accountUrl = "";
        String key = "";
        if(StrUtil.isNotBlank(openKfId)){
            key = getKey(openKfId);
            accountUrl = redisCache.getCacheObject(key);
            if (StrUtil.isNotBlank(accountUrl)) {
                return accountUrl;
            }
        }

        // 1.先获取玫丽平台客服
        LambdaQueryWrapper<Corp> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.like(Corp::getName, "玫丽平台");
        wrapper3.last(" ORDER BY RAND() LIMIT 1 ");
        Corp corp3 = getOne(wrapper3);
        if (BeanUtil.isNotEmpty(corp3)) {
            accountUrl = corp3.getKfUrl();
        }

        // 2.根据客服id获取
        Corp corp = getById(openKfId);
        if (BeanUtil.isNotEmpty(corp)) {
            accountUrl = corp.getKfUrl();
        } else {
            /**
             * 3.根据openKfId获取不到客服链接
             * 情况1：若是openKfId是以KF开头的，则表示为历史数据，则根据name，判断是什么客服；
             */
            if(StrUtil.isNotBlank(openKfId) && (openKfId.substring(0, "KF".length())).equals("KF")){
                LambdaQueryWrapper<Corp> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.like(Corp::getName, name);
                wrapper2.last(" ORDER BY RAND() LIMIT 1 ");
                Corp corp2 = getOne(wrapper2);
                if (BeanUtil.isNotEmpty(corp2)) {
                    accountUrl = corp2.getKfUrl();
                }
            }
        }

        if (StrUtil.isNotBlank(accountUrl)) {
            redisCache.setCacheObject(key, accountUrl);
            return accountUrl;
        }
        String url = ACCOUNT_URL.concat(getAccessToken());
        JSONObject params = new JSONObject();
        params.put("open_kfid", openKfId);
        JSONObject result = doPost(url, params);
        if (result.getString("errmsg").equals("ok")) {
            accountUrl = result.getString("url");
        }
        redisCache.setCacheObject(key, accountUrl);
        return accountUrl;
    }

    private String getAccessToken() {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;
        String result = HttpUtil.get(url);
        if (StrUtil.isNotBlank(result)) {
            JSONObject object = JSON.parseObject(result);
            return object.getString("access_token");
        }
        return "";
    }

    private JSONObject doPost(String url, JSONObject params) {
        String result = HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .body(params.toJSONString())
                .execute()
                .body();
        return JSON.parseObject(result);
    }

    private String getKey(String open_kfid) {
        return Constants.MERRY_CONFIG_KEY.concat("corp:").concat(open_kfid);
    }
}

